<template>
  <div ref="parentDiv">
    <Window
      :show="windowConfig.show"
      :width="width"
      :height="height"
      :buttons="windowConfig.buttons"
      @close="closeWindow"
    >
      <el-form
        ref="blogFormRef"
        :model="blogFormData"
        :rules="rules"
        style="display: flex; flex-direction: column; flex: auto"
      >
        <el-form-item prop="title">
          <div class="title-input">
            <el-input
              placeholder="起一个好听的名字"
              v-model="blogFormData.title"
              ><template #prefix
                ><span class="iconfont icon-title"></span></template
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item prop="content" class="textArea">
          <!-- <div :style="{'width':'100%','background':'green','flex':'auto'}">
            
          </div> -->
          <div style="width: 100%; height: 100%">
            <EditorHtml
              v-if="blogFormData.editorType == 0"
              v-model="blogFormData.content"
            ></EditorHtml>
            <EditorMarkdown
              v-else
              @htmlContent="setHtmlContent"
              v-model="blogFormData.markdownContent"
            ></EditorMarkdown>
          </div>
        </el-form-item>
      </el-form>
      <Dialog
        :show="dialogConfig.show"
        :title="dialogConfig.title"
        :buttons="dialogConfig.buttons"
        width="600px"
        @close="dialogConfig.show = false"
      >
        <el-form
          ref="settingFormRef"
          :model="blogFormData"
          :rules="rules"
          label-width="80px"
          class="blog-setting-form"
        >
          <el-form-item label="博客分类" prop="categoryId">
            <el-select
              v-model="blogFormData.categoryId"
              clearable
              placeholder="请选择分类"
            >
              <el-option
                v-for="(item, index) in categoryList"
                :key="index"
                :value="item.categoryId"
                :label="item.categoryName"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <CoverUpload v-model="blogFormData.cover"></CoverUpload>
          </el-form-item>
          <el-form-item label="博客类型" prop="type">
            <el-radio-group v-model="blogFormData.type">
              <el-radio :label="0">原创</el-radio>
              <el-radio :label="1">转载</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="原文地址"
            prop="reprintUrl"
            v-if="blogFormData.type == 1"
          >
            <el-input
              placeholder="填写原文地址"
              v-model="blogFormData.reprintUrl"
              ><template #prefix
                ><span class="iconfont icon-zhuanzai"></span></template
            ></el-input>
          </el-form-item>
          <el-form-item label="评论" prop="allowComment">
            <div class="allow-comment">
              <el-radio-group v-model="blogFormData.allowComment">
                <el-radio :label="1">允许</el-radio>
                <el-radio :label="0">不允许</el-radio>
              </el-radio-group>
              <span class="info">先设置好相应参数,评论才会生效</span>
            </div>
          </el-form-item>
          <el-form-item label="简介" prop="summary">
            <el-input
              placeholder="这里写简介"
              v-model="blogFormData.summary"
              size="large"
              type="textarea"
              :autosize="{ minRows: 4, maxRow: 4 }"
            ></el-input>
          </el-form-item>
          <el-form-item label="博客标签" prop="tag">
            <div class="tag-input-panel">
              <div class="tag-list">
                <el-tag
                  v-for="(item, index) in blogFormData.tag"
                  :key="index"
                  @close="deleteTag(index)"
                  closable
                  class="tag-item"
                >
                  {{ item }}
                </el-tag>
                <span class="info" v-if="blogFormData.tag.length == 0"
                  >打个tag先</span
                >
                <el-icon
                  class="iconfont icon-tianjia"
                  @click="showTagInputHandler"
                  v-if="!showTagInput"
                ></el-icon>
                <el-input
                  class="tag-input"
                  v-if="showTagInput"
                  v-model="tagInputValue"
                  @blur="tagInputResult"
                  @keyup.enter="tagInputResult"
                ></el-input>
              </div>
            </div>
          </el-form-item>
        </el-form>
      </Dialog>
    </Window>
  </div>
</template>

<script setup>
import {
  ref,
  computed,
  reactive,
  getCurrentInstance,
  onMounted,
  nextTick,
  onUnmounted,
} from "vue";
const { proxy } = getCurrentInstance();

const api = {
  loadDataList: "/category/loadAllCategory4Blog",
  saveBlog: "/blog/saveBlog",
  getUserInfo: "/getUserInfo",
  getBlogDetail: "/blog/getBlogById",
  autoSaveBlog: "/blog/autoSaveBlog",
};

const props = defineProps({
  width: {
    type: Number,
    required: true,
  },
  height: {
    type: Number,
    required: true,
  },
  buttons: {
    type: Array,
  },
  showCancel: {
    type: Boolean,
    default: true,
  },
  show: {
    type: Boolean,
    default: false,
  },
});

const rules = {
  title: [{ required: true, message: "请填写标题" }],
  content: [{ required: true, message: "请填写文章内容" }],
  categoryId: [{ required: true, message: "请选择博客分类" }],
  type: [{ required: true, message: "请选择博客类型" }],
  allowComment: [{ required: true, message: "请选择是否允许评论" }],
  reprintUrl: [{ required: true, message: "请输入原文地址" }],
};

const loadCategory = async () => {
  let result = await proxy.Request({
    url: api.loadDataList,
  });
  if (!result) {
    return;
  }
  categoryList.value = result.data;
};

// 自动保存
let timer = ref(null);

const startTimer = () => {
  timer.value = setInterval(() => {
    autoSave();
  }, 10000);
};

const cleanTimer = () => {
  if (timer.value != null) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

const autoSave = async () => {
  if (
    (blogFormData.value.title == undefined &&
      blogFormData.value.content == undefined) ||
    timer.value == null ||
    dialogConfig.show
  ) {
    return;
  }
  const params = {};
  Object.assign(params, blogFormData.value);
  let result = await proxy.Request({
    url: api.autoSaveBlog,
    params: params,
  });
  if (!result) {
    return;
  }
  blogFormData.value.blogId = result.data;
};

// 博客内容 新增,修改

// Markdown编辑器回调html
const setHtmlContent = (htmlContent) => {
  blogFormData.value.content = htmlContent;
};

// 博客正文
const blogFormRef = ref({});
const blogFormData = ref({ tag: [] });

// 第一步提交
const windowConfig = ref({
  show: false,
  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        blogFormRef.value.validate(async (valid) => {
          if (!valid) {
            return;
          }
          showSettings();
        });
      },
    },
  ],
});

// 博客设置
const dialogConfig = reactive({
  show: false,
  title: "博客设置",

  buttons: [
    {
      type: "primary",
      text: "确定",
      click: (e) => {
        submitBlog();
      },
    },
  ],
});

const showSettings = () => {
  dialogConfig.show = true;
};

const emit = defineEmits();
const closeWindow = () => {
  windowConfig.value.show = false;
  emit("callback");
  cleanTimer();
};

// 初始化
const init = (type, data) => {
  windowConfig.value.show = true;

  startTimer();

  nextTick(() => {
    if (blogFormRef.value) {
      blogFormRef.value.resetFields();
      blogFormData.value = { tag: [] };
    }
  });
  if (type === "add") {
    getUserInfo();
  } else if (type === "update") {
    getBlogDetail(data.blogId);
  }
};
defineExpose({ init });

const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo,
  });
  if (!result) {
    return;
  }
  blogFormData.value.editorType = result.data.editorType;
  console.log(blogFormData.value);
};

const getBlogDetail = async (blogId) => {
  let result = await proxy.Request({
    url: api.getBlogDetail,
    params: {
      blogId: blogId,
    },
  });
  if (!result) {
    return;
  }
  blogFormData.value = result.data;
  if (result.data.tag) {
    blogFormData.value.tag = result.data.tag.split("|");
  } else {
    blogFormData.value.tag = [];
  }
};

// 是否显示tag输入框/输入按钮
const showTagInput = ref(false);
const showTagInputHandler = () => {
  showTagInput.value = true;
};

// tag输入框的值
const tagInputValue = ref(null);
// 失焦/回车触发的方法
const tagInputResult = () => {
  showTagInput.value = false;
  if (tagInputValue.value == undefined) {
    return;
  }
  if (blogFormData.value.tag.indexOf(tagInputValue.value) === -1) {
    blogFormData.value.tag.push(tagInputValue.value);
  }
  tagInputValue.value = undefined;
};
// 删除标签
const deleteTag = (index) => {
  blogFormData.value.tag.splice(index, 1);
};

// 第二部提交 提交设置
// 参数定义

const settingFormRef = ref();
const submitBlog = () => {
  settingFormRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }

    const params = {};
    Object.assign(params, blogFormData.value);
    params.tag = params.tag.join("|");
    let result = await proxy.Request({
      url: api.saveBlog,
      params: params,
    });
    if (!result) {
      return;
    }
    proxy.Message.success("保存博客成功");
    dialogConfig.show = false;
    closeWindow();
  });
};

// 博客分类
const categoryList = ref([]);

onMounted(() => {
  loadCategory();
});
onUnmounted(() => {
  cleanTimer();
});
</script>



<style scoped lang="scss">
::v-deep(.is-error .title-input .el-input__wrapper) {
  box-shadow: none;
}

::v-deep(.textArea) {
  align-self: stretch;
  height: calc(90vh - 181px);
}

.title-input {
  width: 100%;
  border-bottom: 1px solid #dddddd;
  ::v-deep(.el-input__wrapper) {
    box-shadow: none;
  }
}

.blog-setting-form {
  .allow-comment {
    display: flex;
    .info {
      margin-left: 10px;
      color: rgb(76, 78, 88);
      font-size: 13px;
    }
  }

  .tag-input-panel {
    display: flex;
    align-items: center;
    .info {
      margin-right: 10px;
      color: rgb(76, 78, 88);
      font-size: 13px;
    }
    .iconfont {
      cursor: pointer;
    }
    .tag-input {
      width: 100px;
    }
    .tag-list {
      display: flex;
      flex-wrap: wrap;
      .tag-item {
        margin-right: 10px;
        margin-bottom: 5px;
      }
    }
  }
}
</style>